from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from index import models, serializers

@api_view(http_method_names=('GET', 'POST', 'PATCH'))
@permission_classes((AllowAny,))
def movies(request):
    context = {'request': request}

    if request.method == 'GET':
        data = serializers.MovieSerializer(models.Movie.objects.all(), many=True, context=context).data
    else:
        serializer = serializers.MovieSerializer(data=request.data, context=context)

        valid = serializer.is_valid()

        if not valid:
            return Response(serializer.errors, status=400)

        serializer.save()

        data = serializer.data

    return Response(data)
